package com.example.administrator.schoolblog;

import android.app.Activity;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.schoolblog.Beans.BlogUser;
import com.jaeger.library.StatusBarUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends BaseActivity {
    private static final int CODE_ING = 1;   //已发送，倒计时
    private static final int CODE_REPEAT = 3;  //发送失败
    private static final int SMSDDK_HANDLER = 4;  //验证失败
    private static final int VERIFY_SUCCESS = 2;//短信验证成功
    private static final int REGISTER_SUCCESS = 5;//注册成功
    private static final int REGISTER_ERROR = 6;//注册失败
    private String APP_Key="1d777c2d1cc4e";
    private String APP_Secret="c4b8f2a9540be9e8444dd2ba338c66ca";
    private int TIME = 60;//倒计时60s
    private EditText userPhonenum;//手机号文本
    private Button getVerify;//获取验证码按钮
    private EditText register_code;//手机验证码
    private EditText register_pass;//注册密码
    private EditText register_pass_again;//确认密码
    private Button register;//注册按钮
    private TextView return_login;//返回登录
    //主线程UI操作
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CODE_ING:
                    Toast.makeText(RegisterActivity.this, "验证码短信已发送", Toast.LENGTH_SHORT).show();
                    timer.start();
                    break;
                case VERIFY_SUCCESS:
                     userRegister();
                    //Toast.makeText(RegisterActivity.this, "验证成功", Toast.LENGTH_SHORT).show();
                    break;
                case CODE_REPEAT:
                    Toast.makeText(RegisterActivity.this, "验证码发送失败", Toast.LENGTH_SHORT).show();
                    break;
                case SMSDDK_HANDLER:
                    Toast.makeText(RegisterActivity.this, "验证码出错，验证失败", Toast.LENGTH_SHORT).show();
                    //userRegister();
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTransparent(this);
        setContentView(R.layout.blog_register);
        Bmob.initialize(this,"b5d62a501dc94902d3f8672a1b5fc2ab","Bmob");
        initView();
        initSMSSDK();
    }
    //注册初始化函数
    private void initView(){
        userPhonenum=(EditText) findViewById(R.id.register_phonenum);
        getVerify=(Button) findViewById(R.id.get_verify);
        getVerify.setOnClickListener(new OnClickListener());
        register_code=(EditText) findViewById(R.id.register_verify);
        register_pass=(EditText) findViewById(R.id.register_pass);
        register_pass_again=(EditText) findViewById(R.id.register_pass_again);
        register=(Button) findViewById(R.id.register_button);
        register.setOnClickListener(new OnClickListener());
        return_login = (TextView) findViewById(R.id.return_login);
        return_login.setOnClickListener(new OnClickListener());
    }
    /**
     * 注册函数
     */
    private void userRegister(){
        BlogUser BlogUser = new BlogUser();
        String phonenum=userPhonenum.getText().toString().trim();
        String pass = register_pass.getText().toString().trim();
        BlogUser.setNickname(phonenum);
        BlogUser.setPassword(pass);
        BlogUser.setUsername(phonenum);
        BlogUser.setMobilePhoneNumber(phonenum);
        BlogUser.setMobilePhoneNumberVerified(true);
        BlogUser.signUp(new SaveListener<BlogUser>() {
            @Override
            public void done(BlogUser blogUser, BmobException e) {
                if (e==null){
                    Toast.makeText(RegisterActivity.this, "注册成功，请返回登录", Toast.LENGTH_SHORT).show();
                    /*Message return_register_success = new Message();
                    return_register_success.what = REGISTER_SUCCESS;
                    handler.sendMessage(return_register_success);*/
                }else {
                    Toast.makeText(RegisterActivity.this, "注册失败:"+e.toString(), Toast.LENGTH_SHORT).show();
                    /*Message return_register_error = new Message();
                    return_register_error.what=REGISTER_ERROR;
                    handler.sendMessage(return_register_error);*/
                }
            }
        });
    }
    /**
     * 初始化SMSSDK(mob短信验证接口)
     */
    private void initSMSSDK(){
        //初始化短信验证
        SMSSDK.initSDK(this,APP_Key,APP_Secret);
        //注册短信回调
        SMSSDK.registerEventHandler(new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                switch (event)
                {
                    case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE:
                        if(result==SMSSDK.RESULT_COMPLETE){
                            //Toast.makeText(RegisterActivity.this,"验证成功",Toast.LENGTH_SHORT).show();
                            Message return_verify_message = new Message();
                            return_verify_message.what = VERIFY_SUCCESS;
                            handler.sendMessage(return_verify_message);
                        }else {
                            //Toast.makeText(RegisterActivity.this,"验证失败",Toast.LENGTH_SHORT).show();
                            Message return_verify_error = new Message();
                            return_verify_error.what=SMSDDK_HANDLER;
                            handler.sendMessage(return_verify_error);
                        }
                        break;
                    case SMSSDK.EVENT_GET_VERIFICATION_CODE:
                        if (result==SMSSDK.RESULT_COMPLETE){
                            //Toast.makeText(RegisterActivity.this,"获取验证码成功",Toast.LENGTH_SHORT).show();
                            Message get_code_massage = new Message();
                            get_code_massage.what=CODE_ING;
                            handler.sendMessage(get_code_massage);
                        }else {
                            //Toast.makeText(RegisterActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
                            //Log.d("shibai", "获取验证码失败 ");
                            Message get_code_error = new Message();
                            get_code_error.what=CODE_REPEAT;
                            handler.sendMessage(get_code_error);
                        }
                        break;
                    default:
                        ((Throwable)data).printStackTrace();
                }
            }
        });

    }
    /**
     * 事件监听函数
     */
    private class OnClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            String phonenum=userPhonenum.getText().toString().trim();
            String code = register_code.getText().toString().trim();
            String pass = register_pass.getText().toString().trim();
            String pass_again = register_pass_again.getText().toString().trim();
            switch (v.getId()){
                case R.id.get_verify:
                    boolean isPhonenumRighe=verifyThePhone(phonenum);
                    if(isPhonenumRighe==false){
                        Toast.makeText(RegisterActivity.this,"请输入正确格式手机号码",Toast.LENGTH_SHORT).show();
                    }else {
                        //Toast.makeText(RegisterActivity.this,"发送短息哦",Toast.LENGTH_SHORT).show();
                        SMSSDK.getVerificationCode("86",phonenum);
                        //timer.start();
                    }
                    break;
                case R.id.return_login:
                    finish();
                    break;
                case R.id.register_button:
                    if (pass.equals("")||pass_again.equals("")||phonenum.equals("")||code.equals("")){
                        Toast.makeText(RegisterActivity.this, "请填写所有信息", Toast.LENGTH_SHORT).show();
                    }else if (!pass.equals(pass_again)){
                        Toast.makeText(RegisterActivity.this, "两次密码填写不一致", Toast.LENGTH_SHORT).show();
                    }else{
                        SMSSDK.submitVerificationCode("86",phonenum,code);
                    }
            }
        }
    }
    /**
     * 功能：手机格式验证
     */
    public boolean verifyThePhone(String phonenum){
        if(phonenum.length()<0||phonenum.length()>11){
            return false;
        }
        else {
            Pattern p = Pattern.compile("^1[0-9]{10}$");
            Matcher m = p.matcher(phonenum);
            return m.matches();
        }
    }
    /**
     * 使用计时器来限定验证码
     * 在发送验证码的过程 不可以再次申请获取验证码 在指定时间之后没有获取到验证码才能重新进行发送
     * 这里限定的时间是60s
     */
    private CountDownTimer timer=new CountDownTimer(60000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            getVerify.setBackgroundDrawable(getResources().getDrawable(R.drawable.verify_click_selector));
            getVerify.setEnabled(false);
            getVerify.setText((millisUntilFinished/1000)+"秒后重发");
        }

        @Override
        public void onFinish() {
            getVerify.setBackgroundDrawable(getResources().getDrawable(R.drawable.verify_selector));
            getVerify.setEnabled(true);
            getVerify.setText("获取验证码");
        }
    };


}
